package com.atguigu.cloud.service.impl;

import com.atguigu.cloud.mapper.AccountMapper;
import com.atguigu.cloud.service.AccountService;
import io.seata.core.context.RootContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author bairimengchang
 * @version 1.0
 * @project cloud2024
 * @description
 * @date 2024/12/10
 */
@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountMapper accountMapper;

    @Override
    public void decrease(Long userId, Long money) {
        // XID
        String xid = RootContext.getXID();
        log.info("------->account-service中扣减余额开始,XID:{}", xid);
        log.info("------->account-service中扣减余额开始");
        accountMapper.decrease(userId, money);
        myTimeOut();
        log.info("------->account-service中扣减余额结束");
    }

    // 一个超时方法，测试超时访问账户服务的情况。没有事务控制导致库存减少了，账户钱也少了，但订单无法完成
    public void myTimeOut() {
        log.info("myTimeOut start");
        try {
            // Thread.sleep(65000); 底层都一样，让线程暂停65秒
            TimeUnit.SECONDS.sleep(65);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("myTimeOut end");
    }
}
